import time

from matplotlib import pyplot as plt
from selenium.webdriver.common.action_chains import ActionChains
from PIL.Image import Image
from pytesseract import pytesseract
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import numpy as np
list_study = []
num = 0  # 一共几期青年大学习
dict_Name = {}
dict_excle = {}


def check_captach(img_path):
    im = Image.open(img_path)
    num = pytesseract.image_to_string(im)
    return num


def login(username, pwd):
    driver.find_element(By.ID, 'userName').send_keys(username)
    driver.find_element(By.ID, 'password').send_keys(pwd)
    driver.find_element(By.XPATH, '/html/body/div[1]/div/div/div/a').click()


def in_main():
    global dict_Name, dict_excle
    driver.find_element(By.XPATH, '//*[@id="nav"]/div[8]/div[1]/div[1]').click()
    time.sleep(5)

    for handle in driver.window_handles:
        print(driver.title)
        driver.switch_to.window(handle)
        if '青年大学习' in driver.title:
            break
    driver.find_element(By.XPATH, "//span[contains(text(),'数据查看')]").click()
    driver.find_element(By.XPATH,
                        '//*[@id="app"]/div/div[2]/section/div/div[5]/div[3]/table/tbody/tr/td[8]/div/div').click()
    time.sleep(2)
    driver.find_element(By.XPATH, "//span[@class='el-input__suffix-inner']").click()
    time.sleep(2)
    ls = driver.find_elements(By.XPATH, "//li[@class='el-select-dropdown__item']//span[contains(text(),'青年')]")
    for i in ls:
        list_study.append(i.get_attribute("innerText"))
        print(i.get_attribute("innerText"))
        driver.execute_script("arguments[0].click();", i)
        driver.find_element(By.XPATH, "//span[contains(text(),'查询')]").click()  # 查询
        time.sleep(4)
        list_name = getInfo()
        dict_excle[i.get_attribute("innerText")] = list_name
        for name in list_name:
            if name not in dict_Name.keys():
                dict_Name[name] = 1
            else:
                dict_Name[name] += 1
        driver.find_element(By.XPATH, "//span[@class='el-input__suffix-inner']").click()  # 删除第一个
        driver.find_element(By.XPATH, "//span[@class='el-input__suffix-inner']").click()  # 打开下拉框
        if '2022年第18期' in i.get_attribute("innerText"):
            return dict_Name


def getInfo():
    tbody = driver.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/section/div/div[4]/div[3]/table/tbody')
    trs = tbody.find_elements(By.TAG_NAME, 'tr')
    b = [tr.find_element(By.TAG_NAME, 'div').text for tr in trs]
    print(b)
    return b


def writeExcel():
    global dict_excle
    print(dict_excle)
    df = pd.DataFrame(pd.DataFrame.from_dict(dict_excle, orient='index').values.T, columns=list(dict_excle.keys()))
    print(df)
    df.to_excel('青年大学习报告.xlsx','青年大学习', index=False)


def showImg():
    global dict_Name
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.barh(list(dict_Name.keys()), list(dict_Name.values()))
    plt.xlabel('参与青年大学习次数')
    plt.ylabel('学生姓名')
    plt.title('青年大学习”2023年第18期-青年大学习”2022年第18期')
    plt.savefig("study.png")
    plt.show()


if __name__ == '__main__':
    username = 'jsjtu2012'
    pwd = 'jsj@00000'
    url = 'https://tuan.12355.net/bg/index.html'
    driver = webdriver.Chrome()
    driver.get(url)
    # 隐式等待，这样规定了十秒内如果元素未出现则抛出异常
    driver.implicitly_wait(15)
    login(username, pwd)
    # 执行操作
    in_main()
    print("==============")
    print(dict_Name)
    print(list_study)
    showImg()
    writeExcel()
